<template>
  <div class="vehicle-management">

    <div class="card">
      <el-form inline>
        <el-form-item label="车辆类型：">
          <el-input v-model="params.type" placeholder="请输入车辆类型" />
        </el-form-item>

        <el-form-item label="核载人数：">
          <el-input v-model="params.load_capacity" placeholder="请输入核载人数" type="number" max="500" />
        </el-form-item>

        <el-form-item label="车牌号：">
          <el-input v-model="params.license_plate_number" placeholder="请输入车牌号" />
        </el-form-item>

        <el-form-item label="是否可用：">
          <el-select v-model="params.is_available" placeholder="请选择">
            <el-option v-for="item in availableOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否需要审核：">
          <el-select v-model="params.examine" placeholder="请选择">
            <el-option v-for="item in examineOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="danger" @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div style="margin-bottom: 20px;">
        <el-button type="primary" @click="addVehicles">添加车辆信息</el-button>
        <el-button icon="el-icon-refresh-right" @click="resetSearch">刷新</el-button>
      </div>
      <el-table v-loading="loading" :data="list" border stripe>
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="type" label="车辆类型" align="center">
          <template v-slot="{ row }">
            {{ row?.type?.name }}
          </template>
        </el-table-column>
        <el-table-column prop="license_plate_number" label="车牌号" align="center" />
        <el-table-column prop="load_capacity" label="核载人数" align="center" />
        <el-table-column prop="is_available" label="是否可用" align="center">
          <template v-slot="{ row }">
            <i
              style="font-size: 18px;"
              :class="[
                row.is_available ? 'el-icon-check' : 'el-icon-close'
              ]"
            />
          </template>
        </el-table-column>
        <el-table-column prop="examine" label="是否需审核" align="center">
          <template v-slot="{ row }">
            <i
              style="font-size: 18px;"
              :class="[
                row.examine === 1 || row.examine === null
                  ? 'el-icon-close' : 'el-icon-check'
              ]"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button size="mini" type="primary" @click="editVehicle(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="removeVehicle(row)">删除</el-button>
            <el-button size="mini" type="info" @click="toInfo(row)">信息</el-button>
          </template>

        </el-table-column>
      </el-table>

      <div class="pagination">
        <Pagination
          v-if="total"
          style="margin-top: 0; padding-bottom: 0;"
          :total="total"
          :limit="params.paginate"
          :page="params.page"
          @pagination="pagination"
        />
      </div>
    </el-card>

    <AddVehicleDialog v-model="addVehicleDialogShow" @onConfirm="addVehicleConfirm" />

    <EditVehicleDialog v-model="currentVehicle" :visible.sync="editVehicleDialogShow" @onConfirm="editVehicleConfirm" />
  </div>
</template>

<script>
import {
  getVehiclesList,
  deleteVehicleResource,
  addVehicleResource,
  editVehicleResource
} from '@/api/vehicleService'
import AddVehicleDialog from '@/views/vehicleService/components/vehicleManagement/AddVehicleDialog.vue'
import EditVehicleDialog from '@/views/vehicleService/components/vehicleManagement/EditVehicleDialog.vue'
import Pagination from '@/components/Pagination/index.vue'
export default {
  name: '',
  components: {
    Pagination,
    AddVehicleDialog,
    EditVehicleDialog
  },
  data() {
    return {
      loading: false,
      list: [],
      addVehicleDialogShow: false,
      editVehicleDialogShow: false,
      currentVehicle: null,
      total: 0,
      params: {
        paginate: 10,
        page: 1,
        type: null,
        load_capacity: null,
        license_plate_number: null,
        is_available: null,
        examine: null
      },
      availableOptions: [
        { value: 'fail', label: '不可用' },
        { value: 1, label: '可用' }
      ],
      examineOptions: [
        { value: 'no', label: '需审核' },
        { value: 'yes', label: '无需审核' }
      ]
    }
  },
  created() {
    this.getVehiclesList()
  },
  methods: {
    pagination(e) {
      this.params.page = e.page
      this.params.paginate = e.limit
      this.refresh()
    },
    async getVehiclesList() {
      this.loading = true
      try {
        const res = await getVehiclesList(this.params)
        console.log('res --------->', res)
        this.list = res.data.data
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      } finally {
        await this.sleep(300)
        this.loading = false
      }
    },

    removeVehicle(row) {
      console.log('row --------->', row)
      this.$confirm(
        '是否删除该项？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.removeVehicleFetch(row.id)
      })
    },

    async removeVehicleFetch(params) {
      try {
        await deleteVehicleResource(params)
        this.$message.success('删除成功')
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '删除失败')
      }
    },

    addVehicles() {
      this.addVehicleDialogShow = true
    },

    async addVehicleConfirm(e) {
      try {
        await this.addVehicleFetch(e)
        this.$message.success('添加成功')
        this.refresh()
      } catch (error) {
        this.$message.error(error?.message || '添加失败')
      }
    },

    async addVehicleFetch(data) {
      const res = await addVehicleResource(data)
        .catch(err => {
          throw new Error(err?.response?.data?.message || '添加失败')
        })

      if (res.code !== 200) {
        throw new Error('添加失败')
      }

      return res
    },

    editVehicle(row) {
      console.log('row --------->', row)
      const { id, is_available, license_plate_number, load_capacity, type, examine, imei } = row
      this.currentVehicle = {
        id,
        is_available,
        license_plate_number,
        load_capacity,
        type: type ? type.id / 1 : null,
        examine,
        imei
      }
      this.editVehicleDialogShow = true
    },

    async editVehicleConfirm(e) {
      try {
        await this.editVehicleFetch(e)
        this.$message.success('修改成功')
        this.refresh()
        this.currentVehicle = null
      } catch (error) {
        this.$message.error(error?.message || '修改失败')
      }
    },

    async editVehicleFetch(data) {
      const res = await editVehicleResource(data)
        .catch(err => {
          throw new Error(err?.response?.data?.message || '修改失败')
        })

      if (res.code !== 200) {
        throw new Error('添加失败')
      }

      return res
    },

    handleSearch() {
      this.params.page = 1
      this.refresh()
    },

    resetSearch() {
      this.params = this.$options.data().params
      this.refresh()
    },

    refresh() {
      this.getVehiclesList()
    },

    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },
    toInfo(row) {
      this.$router.push({
        path: '/vehicle-service/gps/info/' + row.id
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.vehicle-management {
  padding: 20px;

  .card {
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 20px;
    padding: 20px 20px 0 20px;
  }

  ::v-deep(.el-form-item) {
    margin-bottom: 20px;
    //margin-right: 20px;
  }

  .pagination {
    display: flex;
    justify-content: end;
  }
}

::v-deep(.el-card) {
  border: none;
}
</style>
